package com.estore.service;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ShoppingCartService implements Serializable {
    private static final long serialVersionUID = 1L;
    private final String cartFilePath;
    private Map<String, Integer> cart;

    public ShoppingCartService() {
        this("cart.dat");
    }

    public ShoppingCartService(String cartFilePath) {
        this.cartFilePath = cartFilePath;
        loadCart();
    }

    @SuppressWarnings("unchecked")
    private void loadCart() {
        File file = new File(cartFilePath);
        if (!file.exists()) {
            this.cart = new HashMap<>();
            return;
        }

        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
            this.cart = (Map<String, Integer>) in.readObject();
            System.out.println("购物车数据加载成功！商品数量: " + cart.size());
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("购物车数据加载失败: " + e.getMessage());
            this.cart = new HashMap<>();
        }
    }

    public void saveCart() {
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cartFilePath))) {
            out.writeObject(cart);
            System.out.println("购物车数据保存成功！");
        } catch (IOException e) {
            System.err.println("购物车数据保存失败: " + e.getMessage());
        }
    }

    public void addItem(String productId, int quantity) {
        cart.put(productId, cart.getOrDefault(productId, 0) + quantity);
        saveCart(); // 自动保存
    }

    public void updateItem(String productId, int quantity) {
        if (quantity <= 0) {
            cart.remove(productId);
        } else {
            cart.put(productId, quantity);
        }
        saveCart(); // 自动保存
    }

    public void removeItem(String productId) {
        cart.remove(productId);
        saveCart(); // 自动保存
    }

    public void clearCart() {
        cart.clear();
        saveCart(); // 自动保存
    }

    public Map<String, Integer> getCart() {
        return new HashMap<>(cart);
    }

    public int getItemCount() {
        return cart.size();
    }

    public int getTotalQuantity() {
        return cart.values().stream().mapToInt(Integer::intValue).sum();
    }
}